﻿Imports System
Imports System.IO
Imports System.Text
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Threading


Public Class DataCollector
    Private m_thMain As System.Threading.Thread
    Private m_booMustStop As Boolean
    Public Name As String
    Private CURL As cURLPush

    ''' <summary>
    ''' Stops the currently running thread.
    ''' </summary>
    ''' <remarks>This method stops the currently running thread by setting a stop value.</remarks>
    Public Sub StopWork()
        m_booMustStop = True
        If Not m_thMain Is Nothing Then
            If Not m_thMain.Join(100) Then
                m_thMain.Abort()
            End If
        End If
    End Sub

    ''' <summary>
    ''' Begins the process of collecting data to pass to the cURLPush class.
    ''' </summary>
    ''' <param name="arylstDoWorkArgs"></param>
    ''' <remarks>This thread is started from the Worker class thread and multiple instances of these 'children' may be present at any given time.</remarks>
    Public Sub DoWork(ByVal arylstDoWorkArgs As Object)
        m_thMain = System.Threading.Thread.CurrentThread

        'Setup our string variables
        Dim SyncID As Integer = Nothing 'SyncID used to update the metadata
        Dim ProjectID As String = "" 'ProjectID used in the push calls
        Dim DataTemplateID As Integer = Nothing 'DataTemplateID used in the push calls
        Dim FileName As String = "" 'FileName used in the push calls

        'Connect to the database
        Dim conn As New SqlConnection(DataMonitor.SetConnectionString())
        Dim reader As SqlDataReader = Nothing
        Dim reader2 As SqlDataReader = Nothing
        Dim sb As New StringBuilder
        Dim lastDate As DateTime = "1/1/1900 00:00:00"
        Dim TotalRows As Integer = 0
        Dim TotalColumns As Integer = 0
        Dim UTCOffset As Double = 0


        Try
            'Get the new records
            'Open the sql server connection
            conn.Open()

            'Select all of the records in the specified view
            '9/15/2011: Changed this statement to include an order by statement and limit it to 10 records at a time.
            '10/3/2011: Removing the throttling.
            Dim cmd As New SqlCommand("SELECT * FROM dbo." & CStr(arylstDoWorkArgs(0)) & " ORDER BY CAST(LocalDateTime AS SMALLDATETIME)", conn)

            '10/3/2011: Upping the command timeout to 5 minutes from 30 seconds to account for sql express on slow dev machines.
            cmd.CommandTimeout = (300)
            reader = cmd.ExecuteReader()

            'Get the rows and columns count
            TotalColumns = reader.FieldCount


            'read the new records into a string that will be later used in a memory stream and sent to the hub
            While reader.Read()
                For i As Integer = 0 To reader.FieldCount - 1
                    If i = reader.FieldCount - 1 Then
                        sb.Append(reader(i))
                    Else
                        'TODO: This portion of the code is just getting the last record.  This is not necessary as the hub will return this data in it's JSON string.
                        '10/3/2011: I may want to think about reimplementing this along with a throttling function.
                        'If i = 0 Then
                        '    If reader(0) > lastDate Then
                        '        lastDate = reader(0)
                        '    End If
                        'End If
                        'TODO: Try casting our datetime values to actual dates and times rather than going straight to a string since we're losing our midnight '00:00:00'
                        sb.Append(reader(i) & ",")
                    End If
                Next
                TotalRows += 1
                sb.Append(Environment.NewLine)
            End While

            If Not reader.IsClosed Then
                reader.Close()
            End If

            'Get the last synchronization information for this dataset
            If conn.State = ConnectionState.Closed Then
                conn.Open()
            End If

            'Create and execute a new command to retrieve metadata
            cmd = New SqlCommand("EXEC dbo.usp_GetSyncMetadataByParentTable '" & arylstDoWorkArgs(0).ToString & "'", conn)
            reader2 = cmd.ExecuteReader()

            'get the ProjectID, DataTemplateID, and FileName from the reader
            While reader2.Read()
                SyncID = reader2(0).ToString
                ProjectID = reader2(1).ToString
                DataTemplateID = reader2(2).ToString
                FileName = reader2(3).ToString
            End While

            'Move the string into a memory stream and send it to the push method
            Dim cURL As New cURLPush(SyncID, ProjectID, DataTemplateID, FileName, lastDate, TotalRows, TotalColumns)
            Dim ms As New MemoryStream(ASCIIEncoding.Default.GetBytes(sb.ToString))
            ms.Seek(0, SeekOrigin.Begin)
            cURL.Curl2Hub(ms)

        Catch ex As Exception
            System.Diagnostics.EventLog.WriteEntry("VOEIS Hub Push Service", "Error in DataCollector class." & Environment.NewLine & ex.Message.ToString, EventLogEntryType.Error)
            Dim mailer As New NotifyMail()
            mailer.SendServiceMail("VOEIS Hub Push Service - Error", "Error in DataCollector class." & Environment.NewLine & ex.Message.ToString)
        Finally
            If Not reader Is Nothing Then
                reader.Close()
            End If
            If Not reader2 Is Nothing Then
                reader2.Close()
            End If
            conn.Close()

            'Signal to the parent thread that we are done here
            CType(arylstDoWorkArgs(1), ManualResetEvent).Set()
        End Try
    End Sub

End Class
